<template>
	<div>
		<el-container >
			<el-aside width="320px" >
				<el-card>
					<el-tree :data="state.treeList" ref="orgtree" node-key="id" v-loading="state.loading"  :props="state.defaultProps" @node-click="handleNodeClick" :highlight-current="true" :default-expand-all="true">
					</el-tree>
				</el-card>
			</el-aside>
			<el-main>
				<el-card>
					<el-row>
						<el-button  type="success" icon="ele-Edit" @click="addCOrg(ruleFormRef)">新增</el-button>
						<el-button   type="danger" icon="ele-Delete" @click="deleteCOrg(ruleFormRef)" >删除</el-button>
					</el-row>
					<el-form ref="ruleFormRef" :model="state.ruleForm" label-width="100px" :rules="state.rules" >
						<el-row>
								<el-col :span="23">
									<el-form-item label="机构名称" prop="orgName">
										<el-input v-model="state.ruleForm.orgName" :maxlength="50" ></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="12">
									<el-form-item label="机构简称" prop="shortName">
										<el-input v-model="state.ruleForm.shortName" :maxlength="50" ></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="11">
									<el-form-item label="机构编码" prop="orgCode">
										<el-input v-model="state.ruleForm.orgCode" :maxlength="50"  placeholder="机构编码"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="23">
									<el-form-item label="上级机构" prop="parentOrgName">
										<el-input v-model="state.ruleForm.parentOrgName" :disabled="true" ></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="12">
									<el-form-item label="机构级别" prop="orgRank" >
										<DicSelect v-model="state.ruleForm.orgRank" placeholder="请选择机构级别" dicCode="1030" style="width:100%"></DicSelect>
									</el-form-item>
								</el-col>
								<el-col :span="11">
									<el-form-item label="机构分类" prop="orgType" >
										<DicSelect v-model="state.ruleForm.orgType" placeholder="请选择机构分类" dicCode="1029" style="width:100%"></DicSelect>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="12">
									<el-form-item label="状态" prop="orgStatus" >
										<DicSelect v-model="state.ruleForm.orgStatus" placeholder="请选择状态" dicCode="1001" style="width:100%" :excludeIsKey="['100103']"></DicSelect>
									</el-form-item>
								</el-col>
								<el-col :span="11">
									<el-form-item label="排序" prop="ordernum">
										<el-input v-model.number="state.ruleForm.ordernum" type="number" min="0" max="99999999"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row style="text-align: right;margin-right:20px">
								<el-button :loading="state.loading" type="success" icon="ele-Check" @click="submitForm(ruleFormRef)">保存</el-button>
							</el-row>
					</el-form>
				</el-card>
				<el-card>
					<div class="taskDetails-content-title" style="margin-bottom: 10px">
							岗位管理
					</div>
					<div style="text-align:left">
							<el-button  type="success" icon="ele-Plus" @click="addHandle()">新增</el-button>
							<el-button  type="primary" icon="ele-Edit" @click="updateHandle()" :disabled="state.dataListSelections.length !== 1">修改</el-button>
							<el-button  type="primary" icon="ele-Edit" @click="setResEditHandle()" :disabled="state.dataListSelections.length !== 1">设置资源权限</el-button>
							<el-button  type="danger" icon="ele-Delete" @click="deleteResHandle()"  :disabled="state.dataListSelections.length <= 0">清除权限</el-button>
							<el-button  type="danger" icon="ele-Delete" @click="deleteHandle()"  :disabled="state.dataListSelections.length <= 0">删除</el-button>
						</div>
						<el-table :data="state.tableData" stripe style="width: 100%" v-loading="state.dataListLoading"  ref="multipleTable" @selection-change="handleSelectionChange">
								<el-table-column prop="id" type="selection" width="55"/>
								<el-table-column prop="stationCode" label="岗位编码" />
								<el-table-column prop="stationName" label="岗位名称" />
								<el-table-column prop="shortName" label="简称" />
								<el-table-column prop="status" label="状态" column-key="1001" :formatter="formatStatus" />
								<el-table-column prop="stationRank" label="岗位类型" column-key="1031" :formatter="formatStatus"/>
						</el-table>
						<el-pagination
							@size-change="onSelectSizeChange"
							@current-change="onSelectCurrentChange"
							:pager-count="5"
							:page-sizes="[10, 50, 200]"
							v-model:current-page="state.queryForm.page"
							background
							v-model:page-size="state.queryForm.pageSize"
							layout="total, sizes, prev, pager, next, jumper"
							:total="state.total" small>
						</el-pagination>
				</el-card>
			</el-main>
		</el-container>
		<el-dialog :close-on-click-modal="false" :title="!state.stationForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="state.addOrUpdateVisible">
			<el-tabs v-model="state.activeName">
				<el-tab-pane label='岗位信息' name="first" :key="'first'">
					<el-form :model="state.stationForm" :rules="state.stationRule" ref="stationFormRef" @keyup.enter.native="stationFormSubmit(stationFormRef)" label-width="80px">
						<el-form-item label="所属机构" prop="orgName">
							<el-input v-model="state.stationForm.orgName" placeholder="所属机构" :disabled="true"></el-input>
						</el-form-item>
						<el-form-item label="岗位编码" prop="stationCode">
							<el-input v-model="state.stationForm.stationCode" placeholder="岗位编码" :maxlength="50"></el-input>
						</el-form-item>
						<el-form-item label="岗位名称" prop="stationName">
							<el-input v-model="state.stationForm.stationName" placeholder="岗位名称" :maxlength="50"></el-input>
						</el-form-item>
						<el-form-item label="岗位简称" prop="shortName">
							<el-input v-model="state.stationForm.shortName" placeholder="岗位简称" :maxlength="50"></el-input>
						</el-form-item>
						<el-form-item label="状态" prop="status">
							<DicSelect v-model="state.stationForm.status" placeholder="请选择状态" dicCode="1001" style="width:100%" :excludeIsKey="['100103']"></DicSelect>
						</el-form-item>
						<el-form-item label="岗位类型" prop="stationRank">
							<DicSelect v-model="state.stationForm.stationRank" placeholder="请选择状态" dicCode="1031" style="width:100%"></DicSelect>
						</el-form-item>
					</el-form>
				</el-tab-pane>
				<el-tab-pane label="资源" name="second" :key="'second'">
					<el-tree :data="state.stationResTreeList" ref="stationRestree" node-key="id" :props="state.stationDefaultProps"  show-checkbox  :check-strictly="false"  :highlight-current="true">
					</el-tree>
				</el-tab-pane>
			</el-tabs>
			<template #footer>
				<span class="dialog-footer">
					<el-button  @click="state.addOrUpdateVisible = false">取消</el-button>
					<el-button  type="primary" @click="stationFormSubmit(stationFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog :close-on-click-modal="false" title="设置资源权限" ref="setResEdit" v-model="state.setResEditVisible">
			<el-tree :data="state.stationResTreeList" ref="stationRestree" node-key="id" :props="state.stationDefaultProps"  show-checkbox  :check-strictly="false"  :highlight-current="true">
			</el-tree>
			<template #footer>
				<span class="dialog-footer">
					<el-button  @click="state.setResEditVisible = false">取消</el-button>
					<el-button  type="primary" @click="setStationRes">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script setup lang="ts" name="org">
import { nextTick, onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router'
import { FormInstance, ElTree, ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useUserInfo } from '/@/stores/userInfo';
import { storeToRefs } from 'pinia';
import { getDataDictionaryList } from '/@/utils/cacheDic'
import { systemApi } from '/@/api/sys/system-api'
const route = useRoute()
const ruleFormRef = ref<FormInstance>()
const orgtree = ref<InstanceType<typeof ElTree>>()
const stationFormRef  = ref<FormInstance>()
const stationRestree = ref<InstanceType<typeof ElTree>>()
const stores = useUserInfo()
const { userInfos } = storeToRefs(stores)
const state = reactive({
	loading: false,
	dataListLoading: false,
	tenantId: '',
	treeList: [],
	dataDictionaryList: {} as any,
	dataListSelections: [],
	tableData: [],
	defaultProps: {
		children: 'children',
		label: 'orgName'
	},
	ruleForm: {
		id: '',
		orgName: '',
		shortName: '',
		parentOrgName: '',
		ordernum: '',
		orgStatus: '',
		parentId: '',
		orgType: '',
		orgRank: '',
		orgCode: '',
		tenantId: ''
	},
	total: 0,
	totalSelect: 0,
	queryForm: {
		page: 1,
		pageSize: 10,
		param: {
			orgId: '',
			orgName: '',
			stationCode: '',
			stationName: '',
		}
	},
	rules: {
		orgName: [
		{
			required: true,
			message: '机构名称不能为空',
			trigger: 'blur'
		}
		],
		orgStatus: [
		{
			required: true,
			message: '请选择状态',
			trigger: 'change'
		}
		],
		ordernum: [
		{
			type: 'number',
			message: '必须为数字值'
		}
		],
		orgType: [
		{
			required: true,
			message: '请选择机构分类',
			trigger: 'change'
		}
		],
		orgRank: [
		{
			required: true,
			message: '请选择机构级别',
			trigger: 'change'
		}
		],
		orgCode: [
		{
			required: true,
			message: '自定义编码不能为空',
			trigger: 'blur'
		}
		],
		tenantId: [
			{
				required: true,
				message: '请选择租户',
				trigger: 'blur'
			}
		]
	},
	stationForm: {
		id: '',
		orgId: '',
		orgName: '',
		stationCode: '',
		stationName: '',
		shortName: '',
		status: '',
		stationRank: '',
		tenantId: '',
		resId: [] as any,
	},
	addOrUpdateVisible: false,
	stationRule: {
		stationName: [
		{ required: true, message: "岗位名称不能为空", trigger: "blur" }
		],
		stationCode: [
			{ required: true, message: "岗位编号不能为空", trigger: "blur" }
		],
		status: [{ required: true, message: "状态不能为空", trigger: "blur" }]
	},
	activeName: "first",
	stationDefaultProps: {
		children: "children",
		label: "name"
	},
	stationResTreeList: [],
	stationResours: [],
	setResEditVisible: false
})
const getTreeList = (tenantId: string) => {
	systemApi.getOrgsByTenantId(tenantId).then(data => {
		if (data) {
			state.treeList = data.data
		} else {
			state.treeList = []
		}
		state.loading = false;
	}).catch(() => {
		state.loading = false
	})
}
// 页面加载时
onMounted(() => {
	//如果路由传过来就从路由获取租户id，否则直接从store获取当前用户的租户
	if(route.query.tenant){
		state.tenantId = route.query.tenant!.toString()
	} else {
		state.tenantId = userInfos.value.tenantId
	}
	// 数据字典
	getDataDictionaryList(state.dataDictionaryList, ['1001', '1029', '1030', '1031'])
	getTreeList(state.tenantId)
})
const handleNodeClick = (data: any) => {
	state.ruleForm.id = data.id
	state.ruleForm.orgName = data.orgName
	state.ruleForm.shortName = data.shortName
	state.ruleForm.orgStatus = data.orgStatus
	state.ruleForm.parentId = data.parentId
	state.ruleForm.ordernum = data.ordernum
	state.ruleForm.orgType = data.orgType
	state.ruleForm.orgRank = data.orgRank
	state.ruleForm.orgCode = data.orgCode
	state.ruleForm.tenantId = data.tenantId
	if (data.parentId !== "0") {
		state.ruleForm.parentOrgName = orgtree.value!.getNode(data.parentId).data.orgName
		// this.$refs.orgtree.getNode(data.parentId).data.label
	} else {
		state.ruleForm.parentOrgName = ""
	}
	state.queryForm.param.orgId = data.id
	state.queryForm.param.orgName = data.orgName
	queryStationList()
}
const addCOrg = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
	state.ruleForm.tenantId = state.tenantId
	state.ruleForm.id = ''
	if(orgtree.value!.getCurrentNode()){
		state.ruleForm.parentId = orgtree.value!.getCurrentNode().id
		state.ruleForm.parentOrgName = orgtree.value!.getCurrentNode().orgName
	}else{
		ElMessage.error('请选择上级机构')
	}
}
const deleteCOrg = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	if(orgtree.value!.getCurrentNode()){
		if (orgtree.value!.getCurrentNode().childList &&
		orgtree.value!.getCurrentNode().childList.length > 0
		){
			ElMessage.error('请先删除子级机构')
			return false
		}
		ElMessageBox.confirm('是否确定删除所选记录', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
		}).then(() => {
			systemApi.deleteOrgById(state.ruleForm.id).then(data => {
				if (data && data.code === 0) {
					ElMessage.success("删除成功")
					formEl.resetFields()
					state.ruleForm.tenantId = state.tenantId
					state.ruleForm.id = ''
					getTreeList(state.tenantId)
				}else{
					ElMessage.error(data.message)
				}
			}).catch(() => {
				ElMessage.error('删除失败')
			})
		})
	} else {
		ElMessage.error('请选择要删除的机构')
	}
}
const submitForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate((valid: boolean) => {
		if (valid) {
			// 提交数据
			if(!state.ruleForm.parentId){
				ElMessage.error('请选择上级机构')
				return false
			}
			ElMessageBox.confirm('是否确定提交', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				if(state.ruleForm.id){
					systemApi.updateOrg(state.ruleForm).then(data => {
						if (data && data.code === 0) {
							ElMessage.success("保存成功")
							getTreeList(state.tenantId)
						}else{
							ElMessage.error(data.message)
						}
					}).catch(() => {
						ElMessage.error('保存失败')
					})
				}else{
					systemApi.saveOrg(state.ruleForm).then(data => {
						if (data && data.code === 0) {
							ElMessage.success("保存成功")
							getTreeList(state.tenantId)
						}else{
							ElMessage.error(data.message)
						}
					}).catch(() => {
						ElMessage.error('保存失败')
					})
				}
			})
		}
	})
}
const queryStationList = () => {
	state.dataListLoading = true
	systemApi.queryStationList(state.queryForm).then(data => {
		if (data && data.code === 0) {
			state.tableData = data.data.records
			state.total = data.data.totalRow
		} else {
			state.tableData = []
			state.total = 0
		}
	}).finally(() => {
		state.dataListLoading = false
	})
}
const handleSelectionChange = (val: any) => {
	state.dataListSelections = val
}
const onSelectSizeChange = (val: number) => {
	state.queryForm.pageSize = val;
	queryStationList()
}
const onSelectCurrentChange = (val: number) => {
	state.queryForm.page = val;
	queryStationList()
}
const formatStatus = (row: any, column: any, cellValue: string | number, index: number) => {
	if(Object.keys(state.dataDictionaryList).length>0){
		if (cellValue) {
			return state.dataDictionaryList[column.columnKey].get(cellValue)
		}
	}
}
const addHandle = () => {
	if (!orgtree.value!.getCurrentNode()) {
		ElMessage.error('请选择机构')
		return
	}
	state.addOrUpdateVisible = true
	nextTick(() => {
		stationFormRef.value?.resetFields()
		state.stationForm.id = ''
		state.stationForm.orgId = state.queryForm.param.orgId
		state.stationForm.orgName = state.queryForm.param.orgName
		state.stationForm.tenantId = state.tenantId
		state.stationForm.stationCode = ''
		state.stationForm.stationName = ''
		state.stationForm.shortName = ''
		state.stationForm.status = ''
		state.stationForm.stationRank = ''
		systemApi.getTenantStationResTree(state.stationForm.tenantId, '').then(data => {
			if (data) {
				state.stationResTreeList = data.data.tree;
				state.stationResours = data.data.asingRes;
				nextTick(() => {
					checkStation(data.data.asingRes)
				});
			} else {
				state.stationResTreeList = []
			}
		})
	})
}
const checkStation = (asingRes: any) => {
	var checkArray = new Array();
	if (asingRes) {
		asingRes.forEach((item: any, index: number, arr: any) => {
		if (stationRestree.value!.getNode(item.menuId)) {
			if (stationRestree.value!.getNode(item.menuId).isLeaf) {
				checkArray.push(item.menuId)
			}
		}
		});
		nextTick(() => {
			stationRestree.value!.setCheckedKeys(checkArray, false)
		})
	}
}
const updateHandle = () => {
	if (!orgtree.value!.getCurrentNode()) {
		ElMessage.error('请选择机构')
		return
	}
	if (state.dataListSelections.length !== 1) {
		ElMessage.error('请选择一条岗位记录')
		return false;
	}
	state.addOrUpdateVisible = true
	stationFormRef.value?.resetFields()
	state.stationForm.id = state.dataListSelections[0].id
	state.stationForm.orgId = state.queryForm.param.orgId
	state.stationForm.orgName = state.queryForm.param.orgName
	state.stationForm.tenantId = state.tenantId
	state.stationForm.stationCode = state.dataListSelections[0].stationCode
	state.stationForm.stationName = state.dataListSelections[0].stationName
	state.stationForm.shortName = state.dataListSelections[0].shortName
	state.stationForm.status = state.dataListSelections[0].status
	state.stationForm.stationRank = state.dataListSelections[0].stationRank
	systemApi.getTenantStationResTree(state.stationForm.tenantId, state.stationForm.id).then(data => {
		if (data) {
			state.stationResTreeList = data.data.tree;
			state.stationResours = data.data.asingRes;
			stationRestree.value!.setCheckedKeys([], false)
			nextTick(() => {
				checkStation(data.data.asingRes);
			});
		} else {
			state.stationResTreeList = [];
		}
	})
}
const setResEditHandle = () => {
	if (state.dataListSelections.length !== 1) {
		ElMessage.error('请选择一条岗位记录')
		return false;
	}
	state.stationForm.id = state.dataListSelections[0].id
	state.stationForm.orgId = state.queryForm.param.orgId
	state.stationForm.orgName = state.queryForm.param.orgName
	state.stationForm.tenantId = state.tenantId
	state.setResEditVisible = true
	systemApi.getTenantStationResTree(state.stationForm.tenantId, state.stationForm.id).then(data => {
		if (data) {
			state.stationResTreeList = data.data.tree;
			state.stationResours = data.data.asingRes;
			nextTick(() => {
				checkStation(data.data.asingRes);
			});
		} else {
			state.stationResTreeList = [];
		}
	})
}
const deleteResHandle = () => {
	if (state.dataListSelections.length < 1) {
		ElMessage.error('请选择岗位记录')
		return false;
	}
	let ids = state.dataListSelections.map(item => {
		return item.id
	})
	ElMessageBox.confirm('是否确定删除所选记录的资源权限', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
	}).then(() => {
		let loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		systemApi.deleteStationRes(ids).then(data => {
			if (data && data.code === 0) {
				ElMessage.success('处理成功')
				queryStationList()
			} else {
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error("处理失败！")
		}).finally(()=>{
			loading.close()
		})
	})
}
const deleteHandle = () => {
	if (state.dataListSelections.length < 1) {
		ElMessage.error('请选择岗位记录')
		return false;
	}
	let ids = state.dataListSelections.map(item => {
		return item.id
	})
	ElMessageBox.confirm('是否确定删除所选记录', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
	}).then(() => {
		let loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		systemApi.deleteStation(ids).then(data => {
			if (data && data.code === 0) {
				ElMessage.success('处理成功')
				queryStationList()
			} else {
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error("处理失败！")
		}).finally(()=>{
			loading.close()
		})
	})
}
//岗位信息提交
const stationFormSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate((valid: boolean) => {
		if (valid) {
			// 提交数据
			let checkResIds = stationRestree.value!.getCheckedKeys()
			checkResIds = checkResIds.concat(stationRestree.value!.getHalfCheckedKeys())
			state.stationForm.resId = checkResIds
			let loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			if(!state.stationForm.id) {
				// 新增
				systemApi.saveStation(state.stationForm).then(data => {
					if (data && data.code === 0) {
						state.addOrUpdateVisible = false
						queryStationList()
						ElMessage.success('保存成功')
					} else {
						ElMessage.error(data.message)
					}
				}).catch(() => {
					ElMessage.error("保存失败！")
				}).finally(()=>{
					loading.close()
				})
			}else {
				systemApi.updateStation(state.stationForm).then(data => {
					if (data && data.code === 0) {
						state.addOrUpdateVisible = false
						queryStationList()
						ElMessage.success('保存成功')
					} else {
						ElMessage.error(data.message)
					}
				}).catch(() => {
					ElMessage.error("保存失败！")
				}).finally(()=>{
					loading.close()
				})
			}
		}
	})
}
const setStationRes = () => {
	let checkResIds = stationRestree.value!.getCheckedKeys()
	checkResIds = checkResIds.concat(stationRestree.value!.getHalfCheckedKeys())
	let loading = ElLoading.service({
		lock: true,
		text: '处理中',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	systemApi.saveStationRes(state.stationForm.id, checkResIds).then(data => {
		if (data && data.code === 0) {
			state.setResEditVisible = false
			queryStationList()
			ElMessage.success('保存成功')
		} else {
			ElMessage.error(data.message)
		}
	}).catch(() => {
		ElMessage.error("保存失败！")
	}).finally(()=>{
		loading.close()
	})
}
</script>
<style scoped>
.el-main {
    --el-main-padding: 0;
    display: block;
    flex: 1;
    flex-basis: auto;
    overflow: auto;
    box-sizing: border-box;
    padding: var(--el-main-padding);
}
</style>